package com.yansu.cloud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.yansu.cloud.bean.User;
import com.yansu.cloud.service.UserService;

/**
 * 
 * @author 言肃
 * @email yansu_code@126.com
 * @version 1.0
 * @date Jul 23, 2018 6:00:21 PM
 */
@RestController
public class UserController {

	@Value("${spring.application.name}")
	private String APP_NAME;

	@Autowired
	private UserService userService;

	@Autowired
	private EurekaClient eurekaClient;

	@Autowired
	private DiscoveryClient discoveryClient;

	@GetMapping("/simple/{id}")
	public User findById(@PathVariable Long id) {
		return userService.findUserById(id);
	}
	
	@PostMapping("/findAllUsers")
	public List<User> findAllUsers() {
		return userService.getAllUsers();
	}

	@GetMapping("listAll")
	public List<User> listAll() {
		return userService.getAllUsers();
	}
	
	/**
	 * 访问url: http://localhost:9091/eureka-instance
	 * 获取本地服务信息，参数使用application的默认值，配置在provider的spring.application.name
	 * 
	 * @return provider的ip+port配置http://192.168.152.1:9091/
	 */
	@GetMapping("/eureka-instance")
	public String serverUrl() {
		InstanceInfo instance = this.eurekaClient.getNextServerFromEureka(APP_NAME, false);
		return instance.getHomePageUrl();
	}

	/**
	 * 访问url: http://localhost:9091/eureka-info
	 * 获取本地服务信息，相比于/eureku-instance此方法/eureka-info返回更加详尽的信息，
	 * 而且不需要获取本地服务中配置的application信息
	 * 
	 * @return
	 */
	@GetMapping("/eureka-info")
	public ServiceInstance showInfo() {
		ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();
		return localServiceInstance;
	}
}
